package com.fingard.dsp.bank.directbank.citic02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.Calendar;

public class CITIC02Statement extends CITIC02Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        String[] tmpSenderUnderHeader = getSenderUnderStatement(p_reqQrySttm, retAts);
        String tmpSenderUnderTotalNum = retAts.totalNum;
        if (retAts.getWrittenRdCount() == 0) {
            if ("-1".equals(tmpSenderUnderHeader[0])) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSenderUnderHeader[1]);
            } else {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("交易为空");
            }
        } else {
            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpSenderUnderTotalNum)));
        }

        retAts.writeEnd();
        return retAts;
    }

    public String[] getSenderUnderStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};

        String respCode = "";
        String respInfo = "";
        retAts.totalNum = "0";
        int totalNum = 0;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
            if (actItem == null) {
                respHeader[0] = "-1";
                respHeader[1] = "未找到账号[" + p_reqQrySttm.actNum + "]相应商户配置信息!";
                return respHeader;
            }
            boolean isONLINE = false;
            String tmpDownloadFileName = "";
            if (getBankConfig().getValueAsBool("ISONLINE") || "single".equalsIgnoreCase(p_reqQrySttm.batFlag)) {
                //单笔
                int tmpIntDate = 0;
                Calendar tmpCalendarFrom = Calendar.getInstance();
                tmpCalendarFrom.setTime(p_reqQrySttm.getBusDate());
                tmpCalendarFrom.add(Calendar.DATE, 1);
                tmpIntDate = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpDownloadFileName = "S5IP_TOTH_001_ZLDS_" + tmpIntDate + actItem.merchantId + "0001ONLINE.DTL";
                isONLINE = true;
            } else {
            	int tmpIntDate = 0;
                Calendar tmpCalendarFrom = Calendar.getInstance();
                tmpCalendarFrom.setTime(p_reqQrySttm.getBusDate());
                tmpCalendarFrom.add(Calendar.DATE, 1);
                tmpIntDate = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpDownloadFileName = "S5IP_TOTH_001_ZLDS_" + tmpIntDate + actItem.merchantId + "0001BATCH.DTL";
            }
            WriteBankLogLn("FTP对账单文件名:\r\n" + tmpDownloadFileName);
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            MixFtp mixFtp = new MixFtp(ftpSet);
            String localDownloadFilePath = createTempFileDirectory() + File.separator + tmpDownloadFileName;
            FtpReceiver ftpReceiver = mixFtp.downloadFileFromDir(ftpSet.downDir, tmpDownloadFileName, localDownloadFilePath);

            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(localDownloadFilePath, getCharset());
                WriteBankLogLn2("银行返回文件内容:\r\n" + tmpStrRet);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    tmpReader.readLine();

                    while (true) {
                        String eachline = tmpReader.readLine();
                        if (eachline == null) {
                            break;
                        }
                        if (eachline.indexOf('|') > 0) {
                            String[] detailNodes = eachline.split("\\|");
                            RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                            if (isONLINE) {
                                tmpRetDetail.transState = TransState.Success;
                                if (getBankConfig().getValueAsBool("ISALL") && !"AAAAAAA".equals(detailNodes[4])) {
                                    WriteBankLogLn("对账单数据全部返回。");
                                    tmpRetDetail.transState = TransState.Fail;
                                    totalNum++;
                                } else {
                                    if (!"AAAAAAA".equals(detailNodes[4])) {
                                        continue;
                                    }
                                    totalNum++;
                                }
                                tmpRetDetail.askNumber = detailNodes[0];
                                tmpRetDetail.cdFlag = "22";
                                tmpRetDetail.amount = detailNodes[3];
                                tmpRetDetail.busTime = Format.DateTime14Format.format(p_reqQrySttm.getBusDate());
                                tmpRetDetail.oppActName = detailNodes[1];
                                tmpRetDetail.oppAct = detailNodes[2];
                                tmpRetDetail.transMsg = detailNodes[5];
                            } else {
                                tmpRetDetail.transState = TransState.Success;
                                if (getBankConfig().getValueAsBool("ISALL") && !"AAAAAAA".equals(detailNodes[5])) {
                                    WriteBankLogLn("对账单数据全部返回。");
                                    tmpRetDetail.transState = TransState.Fail;
                                    totalNum++;
                                } else {
                                    if (!"AAAAAAA".equals(detailNodes[5])) {
                                        continue;
                                    }
                                    totalNum++;
                                }
                                tmpRetDetail.reqBatchNO = detailNodes[0];
                                tmpRetDetail.askNumber = detailNodes[0] + detailNodes[1];
                                tmpRetDetail.cdFlag = "22";
                                tmpRetDetail.amount = detailNodes[4];
                                tmpRetDetail.busTime = Format.DateTime14Format.format(p_reqQrySttm.getBusDate());
                                tmpRetDetail.oppActName = detailNodes[2];
                                tmpRetDetail.oppAct = detailNodes[3];
                                tmpRetDetail.transMsg = detailNodes[6];
                            }
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    }
                } else {
                    respHeader[0] = "-1";
                    respHeader[1] = "批次结果文件内容为空!";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            respCode = "-1";
            respInfo = e.getMessage();
            WriteBankLogLn(e);
        }

        retAts.totalNum = String.valueOf(totalNum);
        respHeader[0] = respCode;
        respHeader[1] = respInfo;
        return respHeader;
    }
}
